package com.example.mall

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mall.adapter.CartAdapter
import com.example.mall.entity.CartInfo
import com.example.mall.entity.CartRecv
import com.example.mall.entity.GoodsInfo
import com.example.mall.network.CartService
import com.example.mall.network.GoodsService
import com.example.mall.network.ServiceCreator
import com.example.mall.util.ToastUtil
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class CartActivity : AppCompatActivity(), View.OnClickListener, AdapterView.OnItemClickListener,
    AdapterView.OnItemLongClickListener {
    var app : MyApplication?= null
    var tv_count : TextView? =null
    var lv_cart : ListView? =null
    var tv_total_price : TextView? = null
    var ll_empty : LinearLayout? = null
    var ll_content : LinearLayout? = null
    var mCartList  = ArrayList<CartInfo>()
    var goodsList : List<GoodsInfo>? = null
    val goodsService = ServiceCreator.create<GoodsService>()
    val cartService = ServiceCreator.create<CartService>()
    //缓存商品信息
    val mGoodsMap = HashMap<Int, GoodsInfo?>()
    var mCartAdapter : CartAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_cart)
        app = application as MyApplication
        val tv_title = findViewById<TextView>(R.id.tv_title)
        tv_title.setText("购物车")
        lv_cart = findViewById(R.id.lv_cart)
        tv_total_price = findViewById(R.id.tv_total_price)
        tv_count = findViewById(R.id.tv_count)
        tv_count?.setText(app?.cartCount.toString())

        findViewById<ImageView>(R.id.iv_back).setOnClickListener(this)
        findViewById<Button>(R.id.btn_shopping_channel).setOnClickListener(this)
        findViewById<Button>(R.id.btn_clear).setOnClickListener(this)
        findViewById<Button>(R.id.btn_settle).setOnClickListener(this)
        ll_empty = findViewById(R.id.ll_empty)
        ll_content = findViewById(R.id.ll_content)

    }

    override fun onResume() {
        super.onResume()
        showCart()
    }

    private fun showCart() {
        mCartList.clear()
        goodsService.getGoodsList().enqueue(object :
            Callback<List<GoodsInfo>> {
            override fun onResponse(call: Call<List<GoodsInfo>>,
                                    response: Response<List<GoodsInfo>>
            ) {
                goodsList = response.body()
                for(goods in goodsList!!){
                    mGoodsMap.put(goods.id,goods)
                }
                cartService.getCartList(app?.userId!!).enqueue(object :
                    Callback<List<CartRecv>> {
                    override fun onResponse(call: Call<List<CartRecv>>,
                                            response: Response<List<CartRecv>>
                    ) {
                        val cartList = response.body()
                        if (cartList != null) {
                            for(item in cartList){
                                val info = CartInfo()
                                info.goodsId = item.id
                                info.count = item.count
                                info.goods = mGoodsMap.get(info.goodsId)
                                mCartList.add(info)
                            }
                            mCartAdapter = CartAdapter(this@CartActivity,mCartList)
                            lv_cart?.adapter = mCartAdapter
                            lv_cart?.setOnItemClickListener(this@CartActivity)
                            lv_cart?.setOnItemLongClickListener(this@CartActivity)
                            refreshTotalPrice()
                            showCount()
                        }
                    }

                    override fun onFailure(p0: Call<List<CartRecv>>, p1: Throwable) {
                        ToastUtil.show(this@CartActivity,"网络异常1")
                    }
                })
            }

            override fun onFailure(p0: Call<List<GoodsInfo>>, p1: Throwable) {
                ToastUtil.show(this@CartActivity,"网络异常2")
            }
        })


        showCount()
        refreshTotalPrice()
    }


    private fun refreshTotalPrice() {
        var  totalPrice = 0;
        for(info in mCartList){
            val goods = mGoodsMap.get(info.goodsId)
            totalPrice += (goods!!.price * info.count).toInt()
        }
        tv_total_price?.setText(totalPrice.toString())
    }

    private fun showCount() {
        tv_count?.setText(app?.cartCount.toString())

        if(app?.cartCount == 0) {
            ll_empty?.visibility = View.VISIBLE
            ll_content?.visibility = View.GONE
            mCartAdapter?.notifyDataSetChanged()
        }else{
            ll_empty?.visibility = View.GONE
            ll_content?.visibility = View.VISIBLE
        }
    }

    private fun deleteGoods(info: CartInfo) {

        var removed : CartInfo? = null
        for(cartInfo in mCartList){
            if(cartInfo.goodsId == info.goodsId){
                removed = cartInfo
                break
            }
        }
        cartService.deleteCartByGoodId(app?.userId!!,info.goodsId).enqueue(object :
            Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>,
                                    response: Response<ResponseBody>
            ) {
                app?.cartCount = app?.cartCount?.minus(info.count)
                mCartList.remove(removed)
                showCount()
                ToastUtil.show(this@CartActivity,"已从购物车删除"  + mGoodsMap.get(info.goodsId)?.name)
                refreshTotalPrice()
            }

            override fun onFailure(p0: Call<ResponseBody>, p1: Throwable) {
                ToastUtil.show(this@CartActivity,"网络异常")
            }
        })





    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.iv_back -> {finish()}
            R.id.btn_shopping_channel ->{
                val intent = Intent(this,MallActivity::class.java)
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(intent)
            }
            R.id.btn_clear ->{
                cartService.deleteAll(app?.userId!!).enqueue(object :
                    Callback<ResponseBody> {
                    override fun onResponse(call: Call<ResponseBody>,
                                            response: Response<ResponseBody>
                    ) {
                        app?.cartCount = 0
                        showCount()
                        //refreshTotalPrice()
                        ToastUtil.show(this@CartActivity,"购物车已清空")
                    }

                    override fun onFailure(p0: Call<ResponseBody>, p1: Throwable) {
                        ToastUtil.show(this@CartActivity,"网络异常")
                    }
                })


            }
            R.id.btn_settle ->{
                val builder = AlertDialog.Builder(this@CartActivity)
                builder.setTitle("结算商品")
                builder.setMessage("敬请期待")
                builder.setPositiveButton("我知道了",null)
                builder.create().show()
            }
        }
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val intent = Intent(this@CartActivity,DetailActivity::class.java)
        intent.putExtra("goods_id",mCartList.get(position).goodsId)
        startActivity(intent)
    }

    override fun onItemLongClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long): Boolean {
        val info = mCartList.get(position)
        val builder = AlertDialog.Builder(this@CartActivity)
        builder.setMessage("是否从购物车中删除" + info.goods?.name + "?")
        builder.setPositiveButton("是") { dialog, which ->
            mCartList.removeAt(position)
            mCartAdapter?.notifyDataSetChanged()
            deleteGoods(info)
        }
        builder.setNegativeButton("否",null)
        builder.create().show()
        return true
    }
}